package com.wwy.monitor.controller;

//import com.alibaba.buc.sso.client.vo.BucSSOUser;
import com.wwy.monitor.common.ResponseEnum;
import com.wwy.monitor.common.ServiceResponse;
import com.wwy.monitor.model.enumeration.DeleteEnum;
import com.wwy.monitor.model.enumeration.EnableStatusEnum;
import com.wwy.monitor.model.tddl.dto.MonitorAppDTO;
import com.wwy.monitor.model.tddl.dto.MonitorIpDTO;
import com.wwy.monitor.model.tddl.query.MonitorIpQuery;
import com.wwy.monitor.model.vo.CaseVO;
import com.wwy.monitor.model.vo.SimpleCaseVO;
import com.wwy.monitor.service.CaseService;
import com.wwy.monitor.service.MonitorAppService;
import com.wwy.monitor.service.MonitorIpService;
import com.wwy.monitor.util.FormatUtil;
import com.wwy.monitor.util.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping(value = "/api/case")
public class CaseController {
    @Resource(name = "caseThreadPool")
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource(name = "monitorAppService")
    private MonitorAppService monitorAppService;
    @Resource(name = "monitorIpService")
    private MonitorIpService monitorIpService;
    @Resource(name = "caseService")
    private CaseService caseService;

    /**
     * 手动提交
     *
     * @param caseVO
     * @return
     */
    @PostMapping("/submit")
    @ResponseBody
    private ServiceResponse sumbit(HttpServletRequest request, @RequestBody CaseVO caseVO) throws IOException, ServletException {
        ServiceResponse response = new ServiceResponse();
        if (!checkCaseVO(caseVO, response)) {
            return response;
        }
        //使用当前登录用户的邮箱
        BucSSOUser user = UserUtils.getUser(request);
        if (user == null) {
            return ServiceResponse.fail(ResponseEnum.ILLEGAL_OPERATE.getCode(), "请登录后操作");
        }
        if (StringUtils.isBlank(user.getEmailAddr())) {
            return ServiceResponse.fail(ResponseEnum.ILLEGAL_OPERATE.getCode(), "请先为用户配置邮箱");
        }
        threadPoolExecutor.submit(() -> {
            caseService.handleCase(user.getEmailAddr(), caseVO);
        });
        return ServiceResponse.success("请求已提交，请注意查收邮件");
    }

    @PostMapping("/simpleCase")
    @ResponseBody
    public ServiceResponse simpleCase(@RequestBody SimpleCaseVO simpleCaseVO) {
        return ServiceResponse.success(caseService.simpleCase(simpleCaseVO));
    }

    /**
     * 校验case参数
     *
     * @param caseVO
     * @param response
     * @return
     */
    private boolean checkCaseVO(CaseVO caseVO, ServiceResponse response) {
        if (caseVO == null) {
            response = ServiceResponse.paramEmpty("请求不能为空");
            return false;
        }
        if (Objects.isNull(caseVO.getAppId())) {
            response = ServiceResponse.paramEmpty("请选择应用");
            return false;
        }
        if (StringUtils.isBlank(caseVO.getUrl())) {
            response = ServiceResponse.paramEmpty("请求路径不能为空");
            return false;
        }
        if (StringUtils.isBlank(caseVO.getRequestMethod())) {
            response = ServiceResponse.paramEmpty("请求方法不能为空");
            return false;
        }
        if (!FormatUtil.validateHttpMethod(caseVO.getRequestMethod())) {
            response = ServiceResponse.paramEmpty("不支持的请求方法");
            return false;
        }
        if (StringUtils.isNotBlank(caseVO.getParam())) {
            boolean flag = FormatUtil.validateJson(caseVO.getParam());
            if (!flag) {
                response = ServiceResponse.paramEmpty("请求参数请输入JSON格式");
                return false;
            }
        }
        if (StringUtils.isNotBlank(caseVO.getRequestHeader())) {
            boolean flag = FormatUtil.validateJson(caseVO.getRequestHeader());
            if (!flag) {
                response = ServiceResponse.paramEmpty("请求头请输入JSON格式");
                return false;
            }
        }
        if (!checkApp(caseVO.getAppId())) {
            response = ServiceResponse.paramEmpty("无可用应用");
            return false;
        }
        if (!checkIp(caseVO.getAppId())) {
            response = ServiceResponse.paramEmpty("应用无可操作ip");
            return false;
        }
        return true;
    }

    /**
     * 检查应用是否存在
     *
     * @param appId
     * @return
     */
    private boolean checkApp(Long appId) {
        MonitorAppDTO monitorApp = monitorAppService.selectById(appId);
        return (monitorApp != null && EnableStatusEnum.ENABLE.getValue() == monitorApp.getStatus()
                && DeleteEnum.NOT_DELETE.getValue() == monitorApp.getIsDelete());
    }

    /**
     * 检查是否有可用ip
     *
     * @param appId
     * @return
     */
    private boolean checkIp(Long appId) {
        MonitorIpQuery query = new MonitorIpQuery();
        query.setAppId(appId);
        query.setStatus(EnableStatusEnum.ENABLE.getValue());
        query.setIsDelete(DeleteEnum.NOT_DELETE.getValue());
        List<MonitorIpDTO> ipList = monitorIpService.selectByQuery(query);
        return CollectionUtils.isNotEmpty(ipList);
    }
}